//
//  BGShopTableViewController.m
//  bigMall
//
//  Created by ios on 16/7/6.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGShopTableViewController.h"
#import "DropdownMenu.h"
#import "BGShopTableViewCell.h"

#import "BGDateResult.h"
#import "BGShopDataModel.h"

#import "BGFenLeiModel.h"
#import "BGTwoLevelDataModel.h"
#import "MJRefresh.h"

#import "BGAreaResultModel.h"
#import "BGAreaDataModel.h"
#import "MJExtension.h"
//#define _pageNum @"7"
#import "BGShopCellModel.h"
#import "BGGoodInfoViewController.h"

@interface BGShopTableViewController ()<dropdownDelegate>{
    NSArray *_titleArray;
    NSArray *_leftArrat;
    NSArray *_rightArray;
    DropdownMenu *dropdowm;
    NSMutableArray *_dataArray;
    NSUInteger _thisPage;
    NSUInteger _allPage;
    NSString *_catId;
    NSString *_province;
    NSString *_order;
    NSString *_pageNum;
    NSArray *F_oneArray;
    NSArray *F_twoArray;
    NSArray *_areaArray;
    
}


@end

@implementation BGShopTableViewController

- (instancetype)init
{
    if (self = [super init]) {
        
        _pageNum = @"10";
        _order = @"price";
        _province = @"1";
        _catId = @"6";
        NSString *path = [[NSBundle mainBundle]pathForResource:@"area.plist" ofType:nil];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        array = [array firstObject];
        NSMutableArray *oneArray = [NSMutableArray new];
        NSMutableArray *twoArray = [NSMutableArray new];
        for (NSDictionary *model  in array) {
//            NSDictionary *dic = dict.keyValues;/
//            BGAreaDataModel *model = [BGAreaDataModel objectWithKeyValues:dict];
            NSDictionary *dic = @{
                                  @"idStr":model[@"id"],
                                  @"title":model[@"name"]
                                  };
            
            [oneArray addObject:dic];
        }
        [twoArray addObject:oneArray];
        _areaArray = twoArray;
//        [_areaArray writeToFile:@"/Users/LTOVE/Desktop/1xcxx.plist" atomically:YES];
        
    }
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, nil]];
//    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self loadDropMenu];
    
    
//    [self loadAreaData];
    
    
    
    
    
    
    self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    
    
    [self.tableView.header beginRefreshing];

    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    
    
}

- (void)loadDropMenu
{
    
//    dispatch_group_t group = dispatch_group_create();
//    
//    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//    
//
//    
//    dispatch_group_async(group, queue, ^{
//        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
////        [self loadFenleiData];
//        [BGDateResult loadFenLeiWithLevel:@"level" key:@"no" success:^(NSObject *result) {
//            
//            BGFenLeiModel *model = (BGFenLeiModel *)result;
//            
//            NSMutableArray *OneArray = [NSMutableArray new];
//            NSMutableArray *F_twoArrays = [NSMutableArray new];
//            
//            for (BGTwoLevelDataModel *dataModel in model.res) {
//                
//                [OneArray addObject:dataModel.title];
//                NSMutableArray *libianArray = [NSMutableArray new];
//                for (BGTwoLevelDataModel *rightModel in dataModel.children) {
//                    NSDictionary *dict = @{
//                                           @"catId":rightModel.catId,
//                                           @"title":rightModel.title
//                                           };
//                    [libianArray addObject:dict];
//                }
//                [F_twoArrays addObject:libianArray];
//                
//            }
//            F_oneArray = OneArray;
//            [_areaArray writeToFile:@"/Users/LTOVE/Desktop/xcxx.plist" atomically:YES];
//            F_twoArray = F_twoArrays;
//            
//            dispatch_semaphore_signal(semaphore);
//            
//            
//        } failure:^(NSError *error) {
//           dispatch_semaphore_signal(semaphore);
//            
//        }];
//        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//
//    });
//
//    dispatch_group_async(group, queue, ^{
//        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
////        [self loadAreaData];
//        [BGDateResult loadAreaWithStructure:@"recursion" success:^(NSObject *result) {
//            BGAreaResultModel *model = (BGAreaResultModel *)result;
//            NSMutableArray *arr = [NSMutableArray new];
//            NSMutableArray *array = [NSMutableArray new];
//            for (BGAreaDataModel *daModel in model.res) {
//                [arr addObject:daModel.keyValues];
//            }
//            [array addObject:arr];
//            _areaArray = array;
//            //        [array writeToFile:@"/Users/LTOVE/Desktop/xcxx.plist" atomically:YES];
//            dispatch_semaphore_signal(semaphore);
//        } failure:^(NSError *error) {
//            
//            dispatch_semaphore_signal(semaphore);
//        }];
//        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//        
//    });
//    
//    
//    dispatch_group_notify(group, queue, ^{
//        [self testData];
//        [self.tableView reloadData];
//        NSLog(@"%lu",(unsigned long)F_oneArray.count);
//        [_areaArray writeToFile:@"/Users/LTOVE/Desktop/xcxx.plist" atomically:YES];
//        
//        dropdowm = [[DropdownMenu alloc]initDropdownWithButtonTitles:_titleArray andLeftListArray:_leftArrat andRightListArray:_rightArray];
//        dropdowm.delegate = self;
//        self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);
//        //    [self.view addSubview:dropdowm.view];
//        [[UIApplication sharedApplication].keyWindow addSubview:dropdowm.view];
//    });
    
    //加载分类列表
    [self loadFenleiData];
//    //加载地区列表
//    [self loadAreaData];
}

- (void)loadAreaData
{
    [BGDateResult loadAreaWithStructure:@"recursion" success:^(NSObject *result) {
        BGAreaResultModel *model = (BGAreaResultModel *)result;
        NSMutableArray *arr = [NSMutableArray new];
        NSMutableArray *array = [NSMutableArray new];
        for (BGAreaDataModel *daModel in model.res) {
            [arr addObject:daModel.keyValues];
        }
        [array addObject:arr];
        _areaArray = array;
//        [array writeToFile:@"/Users/LTOVE/Desktop/xcxx______aaa.plist" atomically:YES];
        
        
        
        
    } failure:^(NSError *error) {
        
        
    }];
}

//加载分类
- (void)loadFenleiData
{
    [BGDateResult loadFenLeiWithLevel:@"level" key:@"no" success:^(NSObject *result) {
        
        BGFenLeiModel *model = (BGFenLeiModel *)result;
        
        NSMutableArray *OneArray = [NSMutableArray new];
        NSMutableArray *F_twoArrays = [NSMutableArray new];
        
        for (BGTwoLevelDataModel *dataModel in model.res) {
            
            [OneArray addObject:dataModel.title];
            NSMutableArray *libianArray = [NSMutableArray new];
            for (BGTwoLevelDataModel *rightModel in dataModel.children) {
                NSDictionary *dict = @{
                                       @"catId":rightModel.catId,
                                       @"title":rightModel.title
                                       };
                [libianArray addObject:dict];
            }
            [F_twoArrays addObject:libianArray];
            
        }
        F_oneArray = OneArray;
        [_areaArray writeToFile:@"/Users/LTOVE/Desktop/xcxx.plist" atomically:YES];
        F_twoArray = F_twoArrays;
        
        [self testData];
        [self.tableView reloadData];
        NSLog(@"%lu",(unsigned long)F_oneArray.count);
        [_areaArray writeToFile:@"/Users/LTOVE/Desktop/xcxx.plist" atomically:YES];

        dropdowm = [[DropdownMenu alloc]initDropdownWithButtonTitles:_titleArray andLeftListArray:_leftArrat andRightListArray:_rightArray];
        dropdowm.view.height = dropdowm.view.height - 64;
        dropdowm.delegate = self;
        self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);
        //    [self.view addSubview:dropdowm.view];
        [[UIApplication sharedApplication].keyWindow addSubview:dropdowm.view];

        
    } failure:^(NSError *error) {
        
        
    }];
}

-(void)loadMoreData
{
    NSLog(@"dadsa");
    NSLog(@"%ld",_allPage);
    NSLog(@"%ld",_thisPage);
    if (_thisPage > _allPage) {
        
        [self.tableView.footer endRefreshingWithNoMoreData];
        
        return;
    }
    [BGDateResult loadShopHomeDataWithCatId:_catId province:_province order:_order thisPage:[NSString stringWithFormat:@"%ld",_thisPage] pageNum:_pageNum success:^(NSObject *resultData) {
        
        BGShopDataModel *model = (BGShopDataModel *)resultData;
        [self.tableView.footer endRefreshing];
        [_dataArray addObjectsFromArray:model.list];
        [self.tableView reloadData];
        if (model.list.count) {
            
            _thisPage++;
        }
        
    } failure:^(NSError *error) {
        
        
    }];
//    [self.tableView.footer endRefreshingWithNoMoreData];-
    
}
- (void)loadData
{
//    if (!_dataArray.count) {
//        _thisPage = 1;
//    }
    [BGDateResult loadShopHomeDataWithCatId:_catId province:_province order:_order thisPage:@"1" pageNum:_pageNum success:^(NSObject *resultData) {
        //        [self.tableView mj_header];
        self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
        BGShopDataModel *model = (BGShopDataModel *)resultData;
        //        NSLog(@"%@",model.keyValues);
        _dataArray =(NSMutableArray *) model.list;
        _thisPage = 2;
        _allPage = [model.allPage integerValue];
//        _thisPage ++;
        [self.tableView.header endRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
}

/**
 *  刷新表格
 */
- (void)refresh {
    
    [self.tableView.header beginRefreshing];
    
}


#warning 一下为测试数据

- (void)viewWillDisappear:(BOOL)animated {
    
    dropdowm.view.hidden = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    dropdowm.view.hidden = NO;
    
}

//测试数据
- (void)testData {
    [self testTitleArray];
    [self testLeftArray];
    [self testRightArray];
    
}

- (void) testTitleArray {
    _titleArray = @[@"分类", @"地区", @"排序"];
}

//左边列表可为空，则为单下拉菜单，可以根据需要传参
- (void)testLeftArray {
//    NSArray *One_leftArray = @[@"附近", @"熱門商區", @"香洲區", @"斗門區", @"金灣區"];
    
    NSArray *Two_leftArray = [[NSArray alloc] init];
    //    NSArray *R_leftArray = @[@"Test1", @"Test2"];
    NSArray *Three_leftArray = [[NSArray alloc] init];
    
    _leftArrat = [[NSArray alloc] initWithObjects:F_oneArray, Two_leftArray,Three_leftArray, nil];
}

//右边列表不可为空
- (void)testRightArray {
    NSArray *F_rightArray = F_twoArray;
//    NSArray *F_rightArray = @[
//                              @[
//                                  @{@"title":@"500米"},
//                                  @{@"title":@"1000米"},
//                                  @{@"title":@"2000米"},
//                                  @{@"title":@"5000米"}
//                                  ] ,
//                              @[
//                                  @{@"title":@"全部商區"},
//                                  @{@"title":@"拱北"},
//                                  @{@"title":@"香洲"},
//                                  @{@"title":@"吉大"},
//                                  @{@"title":@"華髮商都"},
//                                  @{@"title":@"富華里"},
//                                  @{@"title":@"揚名廣場"},
//                                  @{@"title":@"摩爾廣場"},
//                                  @{@"title":@"井岸鎮"},
//                                  @{@"title":@"紅旗鎮"},
//                                  @{@"title":@"三灶鎮"},
//                                  ],
//                              @[
//                                  @{@"title":@"全部香洲區"},
//                                  @{@"title":@"拱北"},
//                                  @{@"title":@"香洲"},
//                                  @{@"title":@"吉大"},
//                                  @{@"title":@"華髮商都"},
//                                  @{@"title":@"富華里"},
//                                  @{@"title":@"揚名廣場"},
//                                  @{@"title":@"摩爾廣fddfd場"},
//                                  ],
//                              @[
//                                  @{@"title":@"全部斗門區"},
//                                  @{@"title":@"井岸鎮"},
//                                  ],
//                              @[
//                                  @{@"title":@"全部金灣區"},
//                                  @{@"title":@"紅旗鎮"},
//                                  @{@"title":@"三灶鎮"},
//                                  ]
//                              ];
    
//    NSArray *S_rightArray = @[
//                              @[
//                                  @{@"title":@"one"},
//                                  @{@"title":@"two"},
//                                  @{@"title":@"three"}
//                                  ] ,
//                              @[
//                                  @{@"title":@"four"}
//                                  ]
//                              ];
    NSArray *Three_rightArray = @[
                              @[
                                  @{@"title":@"时间"},
                                  @{@"title":@"价格"},
                                  @{@"title":@"库存"}
                                  ] ,
                              @[
                                  @{@"title":@"four"}
                                  ]
                              ];
    
    _rightArray = [[NSArray alloc] initWithObjects:F_rightArray, _areaArray,Three_rightArray, nil];
}
#warning 以上为测试数据


//实现代理，返回选中的下标，若左边没有列表，则返回0
- (void)dropdownSelectedButtonIndex:(NSString *)index LeftIndex:(NSString *)left RightIndex:(NSString *)right {
    NSLog(@"%s : You choice button %@, left %@ and right %@", __FUNCTION__, index, left, right);
    
    int intLeft,intright;
    NSArray *daArray;
    NSDictionary *daDic;
    switch ([index intValue]) {
        case 0:
            
            intLeft = [left intValue];
            intright = [right intValue];
            daArray = F_twoArray[intLeft];
            daDic = daArray[intright];
            _catId = daDic[@"catId"];
            [self refresh];
            break;
        case 1:
            intright = [right intValue];
            daArray = [_areaArray firstObject];
            daDic = daArray[intright];
            _province = daDic[@"idStr"];
            [self refresh];
            
            break;
        case 2:
            switch ([right intValue]) {
                case 0:
                    _order = @"id";
                    [self refresh];
                    break;
                case 1:
                    _order = @"price";
                    [self refresh];
                    break;
                case 2:
                    _order = @"number";
                    [self refresh];
                    break;
                    
                default:
                    break;
            }
            
        default:
            break;
    }
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return _dataArray.count;
//    return 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    BGShopTableViewCell *cell = [BGShopTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
    cell.model = _dataArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 108;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@",indexPath);
    BGGoodInfoViewController *vc = [[BGGoodInfoViewController alloc]init];
    vc.navigationItem.title = @"商品详情";
    vc.hidesBottomBarWhenPushed = YES;
    BGShopCellModel *model = _dataArray[indexPath.row];
    vc.goodId = model.id;
    vc.unit = model.unit;
//    GWLog(@"%@",model.unit);
    
//    vc.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//    self.navigationController.navigationBar.backItem.title = @"";
//    [self.navigationItem.backBarButtonItem setTitle:@""];
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"";
    self.navigationItem.backBarButtonItem = back;
    
    [self.navigationController pushViewController:vc animated:YES];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
